<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model;

use cores\exception\BaseException;
use app\common\model\UserPointsLog as UserPointsLogModel;
use app\common\model\AppPointsLog as AppPointsLogModel;
use app\common\model\OrderCash as OrderCashModel;
use app\common\model\User as UserModel;
use app\api\service\User as UserService;
use app\common\model\AppinfoAppConfig as AppinfoAppConfigModel;
use think\facade\Db;
use app\common\service\ExchangeService;
use app\common\service\ThirdService;

/**
 * 积分模型
 * Class Article
 * @package app\api\model
 */
class Points extends UserPointsLogModel
{

    public function doExchang($data)
    {
        if (!isset($data['value']) || $data['value'] === '' || $data['value'] <= 0) {
            $this->error = '请输入正确的积分数量';
            return false;
        }

        if (!isset($data['appid']) || $data['appid'] == '') {
            $this->error = '请传入应用的appid';
            return false;
        }

        // 查询应用信息
        $appInfo=ExchangeService::getAppInfo($data['appid']);//获取app信息 
        if(!isset($appInfo["code"])||$appInfo["code"]!=1){
            $this->error = '查询应用信息失败';
            return false;

            if(!isset($appInfo['data']["app_interface_config"]["Integral_consumption"])){
                $this->error = '获取配置积分消费接口失败';
                return false;
            }

            if(!isset($appInfo['data']["app_config"]["points_rate"])){
                $this->error = '获取积分兑换汇率失败';
                return false;
            }
        }
        $appConfig=$appInfo['data'];

        // 去查询当前用户的应用积分，判断是否足够扣除（未完成）
        // xxxxxxxxxxx

        // 需变动的商城积分
        $diffMoney = $data['value']/$appConfig["app_config"]['points_rate'];

        // 获取当前登录的用户信息
        $userInfo = UserService::getCurrentLoginUser();
        $userId =$userInfo->user_id;
        $app_user_id =$userInfo->app_user_id;

        try {
            Db::startTrans();
            // 更新账户积分
            (new UserModel)->setInc($userId, 'points', $diffMoney);
            // 新增积分变动记录
            (new UserPointsLogModel())->save([
                'user_id' => $userId,
                'value' => $diffMoney,
                'describe' => "[{$appConfig['app_config']['app_name']}] 应用积分兑换操作",
                'remark' => '应用积分兑换',
                'store_id' =>  \getStoreId(),
            ]);
            // 新增积分兑换记录
            (new AppPointsLogModel())->save([
                'user_id' => $userId,
                'value' => $diffMoney,
                'describe' => "[{$appConfig['app_config']['app_name']}] 应用积分兑换操作",
                'remark' => '应用积分兑换',
                'appid' => $data['appid'],
                'app_value' => $data['value'],
                'store_id' => \getStoreId(),
            ]);

            // 去第三方应用扣除积分
            $Integral_consumption=$appConfig["app_interface_config"]["Integral_consumption"];// 扣除积分接口

            $doPoints=ThirdService::doPoints($Integral_consumption,$data['value'],$app_user_id);
            if(!isset($doPoints['code'])||$doPoints['code']!=1){
                $this->error = json_encode($doPoints);
                return false;
            }
        
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 发生异常，回滚事务
            Db::rollback();
            return false;
        }

        return ['diffMoney'=>$diffMoney,'appConfig'=>$appConfig];
    }

    public function cashExchang($data){
        if (!isset($data['money_type']) || $data['money_type'] == '') {
            $this->error = '请传入兑换货币';
            return false;
        }
        if (!isset($data['type']) || $data['type'] == '') {
            $this->error = '请传入兑换类型';
            return false;
        }
        if (!isset($data['price']) || $data['price'] == '') {
            $this->error = '请传入兑换金额';
            return false;
        }
        if (!isset($data['address']) || $data['address'] == '') {
            $this->error = '请传入收款地址';
            return false;
        }
        if (!isset($data['appid']) || $data['appid'] == '') {
            $this->error = '请传入应用的appid';
            return false;
        }


        // 需变动的商城积分
        if($data['type']==1){//应用积分需先转换成商城积分
            $li['appid']=$data['appid'];
            $li['value']=$data['price'];
            $res=$this->doExchang($li);
           
            if($res){
                $appConfig=$res['appConfig'];
                $diffMoney=(float)$res['diffMoney'];
            }else{
                $this->error = '应用积分兑换失败';
                return false;
            }
            $type_str='USDT';
        }elseif($data['type']==2){//商城积分
            // 查询应用信息
            $appInfo=ExchangeService::getAppInfo($data['appid']);//获取app信息 
            if(!isset($appInfo["code"])||$appInfo["code"]!=1){
                $this->error = '查询应用信息失败';
                return false;

                if(!isset($appInfo['data']["app_interface_config"]["Integral_consumption"])){
                    $this->error = '获取配置积分消费接口失败';
                    return false;
                }

                if(!isset($appInfo['data']["app_config"]["points_rate"])){
                    $this->error = '获取积分兑换汇率失败';
                    return false;
                }
            }
            $appConfig=$appInfo['data'];
            $diffMoney =(float) $data['price'];
            $type_str='PayPal';
        }
 
        // 获取当前登录的用户信息
        $userInfo = UserService::getCurrentLoginUser();
        $userId =$userInfo->user_id;
        $app_user_id =$userInfo->app_user_id;
        $app_user_name =$userInfo->nick_name;

        $points=(new UserModel)->where('user_id',$userId)->value('points');
        if($diffMoney>$points){
            $this->error = '当前积分不足';
            return false;
        }

        try {
            Db::startTrans();
            // 更新账户积分
            (new UserModel)->setDec($userId, 'points', $diffMoney);
            // 新增积分变动记录
            (new UserPointsLogModel())->save([
                'user_id' => $userId,
                'value' => '-'.$diffMoney,
                'describe' => "[{$appConfig['app_config']['app_name']}] $type_str 兑换操作",
                'remark' => $type_str.'兑换',
                'store_id' =>  \getStoreId(),
            ]);
            // 新增现金订单表
            $order_no=date('YmdHis').rand(10000000,99999999);
            (new OrderCashModel())->save([
                'order_no' => $order_no,
                'appid' => $data['appid'],
                'user_id' => $userId,
                'price' => $diffMoney,
                'status' =>0,
                'money_type' => $data['money_type'],
                'store_id' => \getStoreId(),
            ]);
            // 同步给积分兑换平台
            $li['shop_order_no']=$order_no;
            $li['appid']=$data['appid'];
            $li['address']=$data['address'];
            $li['money_type']=$data['money_type'];
            $li['price']=$data['price'];
            $li['app_user_id']=$app_user_id;
            $li['app_user_name']=$app_user_name;
            $appInfo=ExchangeService::placeCash($li);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 发生异常，回滚事务
            Db::rollback();
            return false;
        }

        return true;
    }

}